package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.article.mapper.ArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleService;
import com.heima.common.constant.ESConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.SearchArticleVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleContentMapper articleContentMapper;

    @Autowired
    private ArticleConfigMapper articleConfigMapper;



    /**
     * 加载首页-加载更多-加载更新 三位一体
     *
     * @param dto  type=1 认为是加载更多，type=2表示加载更新
     * @param type
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        //1.非空判断
        if(dto.getSize()==0){
            dto.setSize(10);
        }
        if(dto.getTag()==null){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
//2. 直接调用sql,执行查询(判断类型，排序)
        List<ApArticle> apArticles = articleMapper.loadArticleList(dto, type);
//3.返回数据
        return ResponseResult.okResult(apArticles);
    }
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 保存三剑客
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult save(ArticleDto dto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        //是否存在文档id
        Long id = dto.getId();
        if(id!=null){
            boolean result = this.updateById(apArticle);
            if(result==false){
                return ResponseResult.errorResult( 501,"文章没有找到");
            }
            //修改内容表数据 update ap_article_content set content=? where article_id=?
            articleContentMapper.update(null, Wrappers.<ApArticleContent>lambdaUpdate()
                    .eq(ApArticleContent::getArticleId,apArticle.getId() )
                    .set(ApArticleContent::getContent, dto.getContent()));

        }else{
            boolean save = this.save(apArticle);
            //保存文章配置表数据
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());//文章表id
            config.setIsForward(true); //可转发
            config.setIsComment(true); //可评论
            config.setIsDelete(false); //未删除
            config.setIsDown(false);//未下架
            articleConfigMapper.insert(config);
//保存文章内容表数据
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            articleContentMapper.insert(content);
        }
        // 将新增或修改的文章同步到es索引库中
        SearchArticleVo searchArticleVo = BeanUtil.toBean(apArticle, SearchArticleVo.class);
        rabbitTemplate.convertAndSend
                (ESConstants.ARTICLE_ES_SYNC_TOPIC,
                        ESConstants.ARTICLE_ES_SYNC_KEY,
                        JSONUtil.toJsonStr(searchArticleVo)
                );
        //3.返回数据,要不要返回文章id ，因为wmnews表中需要
        return ResponseResult.okResult(dto.getId());
    }

}
